<template>
  <div>
    <div class="main" v-if="!loading">
      <div class="headCards">
        <!-- 项目统计 -->
        <el-card class="card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span style="font-size: 16px; font-weight: 600">
                <svg-icon icon-class="project-name" class="icons" />项目：
              </span>
              <el-button size="small" type="primary" icon="ArrowLeft" @click="arrowDown">
                展开
              </el-button>
            </div>
          </template>
          <div class="infoList" style="display: flex; flex-direction: column">
            <div style="display: flex">
              <div class="left">
                <div class="infoItem">
                  <svg-icon
                    icon-class="all-item"
                    class="icons"
                    style="width: 16px; height: 16px"
                  />项目总数：
                </div>
                <div class="infoItem">
                  <svg-icon icon-class="money-rmb" class="icons" /> 项目总金额：
                </div>
                <div class="infoItem"><svg-icon icon-class="part" class="icons" />完成项目数：</div>
              </div>
              <div class="right">
                <div class="infoItem">
                  <count-to
                    :start-val="0"
                    :end-val="projectInfo.projectNum"
                    :duration="2000"
                    :autoplay="true"
                  ></count-to>
                </div>
                <div class="infoItem">
                  <count-to
                    :start-val="0"
                    :end-val="projectInfo.projectPrice"
                    :duration="2000"
                    :decimals="2"
                    :autoplay="true"
                  ></count-to>
                </div>
                <div class="infoItem">
                  <count-to
                    :start-val="0"
                    :end-val="projectInfo.finishNum"
                    :duration="2000"
                    :autoplay="true"
                  ></count-to>
                </div>
              </div>
            </div>
            <div>
              <el-progress :percentage="projectInfo.percentage">
                <span>{{ projectInfo.percentage }}%</span>
              </el-progress>
            </div>
          </div>
        </el-card>

        <!-- 新增文件 -->
        <el-card class="card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span style="font-size: 16px; font-weight: 600">
                <svg-icon icon-class="folder" class="icons" />文件归档：
              </span>
            </div>
          </template>
          <div class="infoList">
            <div class="left">
              <div
                class="infoItem"
                style="justify-content: end"
                v-for="item in fileInfo"
                :key="item"
              >
                {{ item?.stateName }}：
              </div>
            </div>
            <div class="right">
              <div class="infoItem" v-for="item in fileInfo" :key="item">
                <count-to
                  :start-val="0"
                  :end-val="item?.count"
                  :duration="2000"
                  :autoplay="true"
                ></count-to>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 采购合同统计 -->
        <el-card class="card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span style="font-size: 16px; font-weight: 600">
                <svg-icon icon-class="procurement" class="icons" />项目采购：
              </span>
            </div>
          </template>
          <div class="infoList">
            <FScrollTable
              :data="procurementInfo.data"
              :columns="procurementInfo.columns"
              :mode="procurementInfo.mode"
              :toggleDur="5000"
              :pageSize="3"
              :border="false"
              align="left"
              :cellStyle="cellStyle"
              style="color: #333; width: 100%"
            >
              <template #icon="{ params }">
                <div style="display: flex; justify-content: space-between">
                  <svg-icon
                    :icon-class="params.row.icon"
                    :style="params?.row?.style"
                    class="icons"
                  />
                  <div>{{ params.row.name }}</div>
                </div>
              </template>
              <template #val="{ params }">
                <div>
                  <div v-if="params.row.noFormat">{{ params.row.val }}</div>
                  <div v-else>{{ numberFormat(params.row.val) }}</div>
                </div>
              </template></FScrollTable
            >
          </div>
        </el-card>

        <!-- 销售合同统计 -->
        <el-card class="card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span style="font-size: 16px; font-weight: 600">
                <svg-icon icon-class="marketing" class="icons" />项目销售：
              </span>
            </div>
          </template>
          <div class="infoList">
            <FScrollTable
              :data="marketingInfo.data"
              :columns="marketingInfo.columns"
              :mode="marketingInfo.mode"
              :toggleDur="5000"
              :pageSize="3"
              :border="false"
              align="left"
              :cellStyle="cellStyle"
              style="color: #333; width: 100%"
            >
              <template #icon="{ params }">
                <div style="display: flex; justify-content: space-between">
                  <svg-icon
                    :icon-class="params.row.icon"
                    class="icons"
                    :style="params?.row?.style"
                  />
                  <div>{{ params.row.name }}</div>
                </div>
              </template>
              <template #val="{ params }">
                <div>
                  <div v-if="params.row.noFormat">{{ params.row.val }}</div>
                  <div v-else>{{ numberFormat(params.row.val) }}</div>
                </div>
              </template></FScrollTable
            >
          </div>
        </el-card>
      </div>
      <div class="headCards">
        <el-card class="card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span style="font-size: 16px; font-weight: 600">
                <svg-icon icon-class="project-name" class="icons" />回款率排前十的项目:
              </span>
            </div>
          </template>
          <MyEcharts :option="projectRankTen"></MyEcharts>
        </el-card>
      </div>
      <div class="headCards">
        <el-card class="card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span style="font-size: 16px; font-weight: 600">
                <svg-icon icon-class="money-rmb" class="icons" />近三年收款、付款金额:
              </span>
            </div>
          </template>
          <MyEcharts :option="threeYearLine"></MyEcharts>
        </el-card>
        <el-card class="card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span style="font-size: 16px; font-weight: 600">
                <svg-icon icon-class="money-rmb" class="icons" />近三年中标的项目金额:
              </span>
            </div>
          </template>
          <MyEcharts :option="threeYearPie"></MyEcharts>
        </el-card>
        <el-card class="card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span style="font-size: 16px; font-weight: 600">
                <svg-icon icon-class="money-rmb" class="icons" />近三年项目合同金额统计:
              </span>
            </div>
          </template>
          <MyEcharts :option="threeYearColumn"></MyEcharts>
        </el-card>
      </div>
    </div>
    <ProjectInfo ref="projectInfoDrawer" />
    <div v-if="loading" class="loading"
      ><FLoading2 text="加载中..." width="120px" height="120px" :duration="2"></FLoading2
    ></div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { numberFormat } from '@/utils/numberFormat.ts'
  import ProjectInfo from './components/projectInfoDrawer.vue'
  import MyEcharts from '@/components/myEcharts/index.vue'
  import CountTo from '@/components/CountTo/index.vue'
  import * as echarts from 'echarts'
  import {
    getHomeProjectMoney,
    getHomeMarketing,
    getHomeProcurement,
    getHomeProjectCount,
    getHomeProjectFile,
    getHomeLineCollectionPayment,
    getHomeBarCollectionRate,
    getHomePieContractPrice,
    getHomeBarAmount,
  } from '@/api/controller/home-controller/index'
  const projectInfo = ref({ projectNum: 0, projectPrice: 0, finishNum: 0, percentage: 0 })
  const projectTab = ref([])
  const projectCount = ref()
  const projectMoney = ref()
  const fileInfo = ref()
  const marketingInfo = ref({
    data: [],
    columns: [
      { prop: 'name', label: '键', width: 140, slot: 'icon' },
      { prop: 'val', label: '值', slot: 'val' },
    ],
    mode: 'page',
  })
  const procurementInfo = ref({
    data: [],
    columns: [
      { prop: 'name', label: '键', width: 140, slot: 'icon' },
      { prop: 'val', label: '值', slot: 'val' },
    ],
    mode: 'page',
  })
  const loading = ref(true)
  const threeYearLine = ref()
  const threeYearPie = ref()
  const threeYearColumn = ref()
  const projectRankTen = ref()
  const baseThreeYearLine = ref({
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      data: ['销售合同收款', '采购合同付款'],
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: [],
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        name: '销售合同收款',
        type: 'line',
        stack: 'Total',
        data: [],
      },
      {
        name: '采购合同付款',
        type: 'line',
        stack: 'Total',
        data: [],
      },
    ],
  })
  const baseThreeYearPie = ref({
    tooltip: {
      trigger: 'item',
    },
    legend: {
      top: '5%',
      left: 'center',
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2,
        },
        label: {
          show: false,
          position: 'center',
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 40,
            fontWeight: 'bold',
          },
        },
        labelLine: {
          show: false,
        },
        data: [],
      },
    ],
  })
  const baseThreeYearColumn = ref({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    legend: {},
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: [
      {
        type: 'category',
        data: [],
      },
    ],
    yAxis: [
      {
        type: 'value',
      },
    ],
    series: [
      {
        name: '销售合同',
        type: 'bar',
        emphasis: {
          focus: 'series',
        },
        label: {
          show: true, // 显示数值
          position: 'top', // 数值显示的位置
        },
        barGap: '50%',
        data: [],
      },
      {
        name: '采购合同',
        type: 'bar',
        emphasis: {
          focus: 'series',
        },
        label: {
          show: true, // 显示数值
          position: 'top', // 数值显示的位置
        },
        barGap: '50%',
        data: [],
      },
    ],
  })
  const baseProjectRankTen = ref({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    xAxis: {
      data: [],
      axisTick: {
        show: false,
      },
      axisLine: {
        show: false,
      },
    },
    grid: {
      left: '3%',
      right: '3%',
      bottom: '5%',
      top: '5%',
      containLabel: true,
    },
    yAxis: {
      axisLine: {
        show: false,
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        color: '#999',
        formatter: '{value}%',
      },
    },
    series: [
      {
        type: 'bar',
        showBackground: true,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' },
          ]),
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#2378f7' },
              { offset: 0.7, color: '#2378f7' },
              { offset: 1, color: '#83bff6' },
            ]),
          },
        },
        data: [],
      },
    ],
  })
  onMounted(async () => {
    initializeApp(
      getHomeProjectMoney().then((res) => {
        projectMoney.value = res.data
        projectInfo.value.projectPrice = res.data[8].price
      }),

      getHomeProjectCount().then((res) => {
        projectCount.value = res.data
        projectCount.value.forEach((item) => {
          if (item.stateName === '已完成') {
            projectInfo.value.finishNum = item.count
          }
          if (item.stateName === '项目总数') {
            projectInfo.value.projectNum = item.count
          }
        })
        projectInfo.value.percentage = Math.round(
          (projectInfo.value.finishNum / projectInfo.value.projectNum) * 100,
        )

        for (let i = 0; i < projectCount.value.length; i++) {
          projectTab.value.push({ ...projectCount.value[i], ...projectMoney.value[i] })
        }
      }),

      getHomeProjectFile().then((res) => {
        fileInfo.value = res.data
      }),

      getHomeProcurement().then((res) => {
        procurementInfo.value.data = [
          {
            name: '合同总数:',
            val: res.data.count,
            icon: 'all-item',
            noFormat: true,
            style: { width: '18px', height: '18px' },
          },
          { name: '合同总金额:', val: res.data.contractAmount, icon: 'money-rmb' },
          { name: '合同总应收:', val: res.data.amountAll, icon: 'money-rmb' },
          { name: '10天内应收:', val: res.data.amount10, icon: 'money-rmb' },
          { name: '20天内应收:', val: res.data.amount20, icon: 'money-rmb' },
          { name: '30天内应收:', val: res.data.amount30, icon: 'money-rmb' },
        ]
      }),

      getHomeMarketing().then((res) => {
        marketingInfo.value.data = [
          {
            name: '合同总数:',
            val: res.data.count,
            icon: 'all-item',
            noFormat: true,
            style: { width: '18px', height: '18px' },
          },
          { name: '合同总金额:', val: res.data.contractAmount, icon: 'money-rmb' },
          { name: '合同总应付:', val: res.data.amountAll, icon: 'money-rmb' },
          { name: '10天内应付:', val: res.data.amount10, icon: 'money-rmb' },
          { name: '20天内应付:', val: res.data.amount20, icon: 'money-rmb' },
          { name: '30天内应付:', val: res.data.amount30, icon: 'money-rmb' },
        ]
      }),

      getHomeBarCollectionRate().then((res) => {
        projectRankTen.value = JSON.parse(JSON.stringify(baseProjectRankTen.value))
        for (let i = 0; i < res.data.length; i++) {
          projectRankTen.value.xAxis.data.push(res.data[i].projectBrief)
          projectRankTen.value.series[0].data.push(res.data[i].collectionRate)
        }
      }),

      getHomeLineCollectionPayment().then((res) => {
        threeYearLine.value = JSON.parse(JSON.stringify(baseThreeYearLine.value))
        for (let i = 0; i < res.data.collectionList.length; i++) {
          threeYearLine.value.xAxis.data.push(res.data.collectionList[i].name)
          threeYearLine.value.series[0].data.push(res.data.collectionList[i].value)
          threeYearLine.value.series[1].data.push(res.data.paymentList[i].value)
        }
      }),

      getHomePieContractPrice().then((res) => {
        threeYearPie.value = JSON.parse(JSON.stringify(baseThreeYearPie.value))
        threeYearPie.value.series[0].data = res.data
      }),

      getHomeBarAmount().then((res) => {
        threeYearColumn.value = JSON.parse(JSON.stringify(baseThreeYearColumn.value))
        for (let i = 0; i < res.data.collectionList.length; i++) {
          threeYearColumn.value.xAxis[0].data.push(res.data.collectionList[i].name)
          threeYearColumn.value.series[0].data.push(res.data.collectionList[i].value)
          threeYearColumn.value.series[1].data.push(res.data.paymentList[i].value)
        }
      }),
    )
  })

  const projectInfoDrawer = ref()
  const arrowDown = () => {
    projectInfoDrawer.value.show(projectTab.value)
  }

  const cellStyle = ({ row, rowIndex, column, columnIndex }) => {
    if (column === 'val') {
      return {
        width: '100%',
        flex: 1,
      }
    }
  }

  const initializeApp = async (...promises: Promise<void>[]) => {
    // loading方法封装成一个函数，参数为发送的请求
    loading.value = true
    try {
      await Promise.all(promises)
    } catch (e) {
      console.error(e)
    } finally {
      loading.value = false
    }
  }
</script>

<style lang="scss" scoped>
  .main {
    margin: 12px;
    .headCards {
      display: flex;
      flex-wrap: wrap;
      .card {
        flex: 1;
        margin: 6px;
        .card-header {
          display: flex;
          justify-content: space-between;
          span {
            flex-shrink: 0;
          }
        }
        .infoList {
          display: flex;
          .left {
            flex-shrink: 0;
            .infoItem {
              justify-content: space-between;
            }
          }
        }
        .infoItem {
          display: flex;
          align-items: center;
          margin: 5px 0;
          height: 1.5em;
          .icons {
            width: 18px;
            height: 18px;
            margin-right: 6px;
          }
        }
        .icons {
          width: 20px;
          height: 20px;
          margin-right: 6px;
        }
      }
    }
  }
  .divider {
    margin: 8px 0;
  }
  .loading {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 80vh;
  }
  :deep(.f-scroll-table__head) {
    display: none;
  }
</style>
